package com.nj.liandi.gulimall.product.exception;

import com.nj.liandi.common.exception.BizeCodeEnume;
import com.nj.liandi.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;


@RestControllerAdvice(basePackages = "com.nj.liandi.gulimall.product.controller")
public class ProductExceptionController {

    private static final Logger logger = LoggerFactory.getLogger(ProductExceptionController.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R HandleValidException(MethodArgumentNotValidException e){
        logger.error("数据校验异常：{}，异常类型是：{},异常：{}",e.getMessage(),e.getClass());
        HashMap<String, String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach(fieldError -> map.put(fieldError.getField(),fieldError.getDefaultMessage()));
        return R.error(BizeCodeEnume.VALID_EXCEPTION.getCode(),BizeCodeEnume.VALID_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value = Exception.class)
    public R HandleException(Throwable throwable){

        logger.error("出现错误异常{}",throwable);
        return R.error(BizeCodeEnume.UNKNOW_EXCEPTION.getCode(),BizeCodeEnume.UNKNOW_EXCEPTION.getMessage());
    }
}
